module TunecoreDirect

  # Represents a individual TuneCore account
  #
  # Required fields are:
  # * email
  # * name
  # * phone_number
  # * postal_code
  # * country
  # * password
  # 
  # Once you set these instance variables you can call Person#create to create the account at TuneCore.  When the account is created the person_id will be 
  # set which you should use to track the user in your system.
  # 
  # If you don't set these instance variables before calling Person#create the call will return false and the Person#errors accessor will be 
  # populated with a list of errors that you will need to fix.
  class TunecoreDirect::Person < TunecoreDirect::Base
    include TunecoreDirect
  
    attr_accessor :person_id, :email, :name, :phone_number, :postal_code, :country, :password, :errors
  
    def initialize(options = {})
      options.each do |k,v|
        self.send("#{k}=", v)
      end
    end
  
    # takes an Rexml::Element and builds a person out of it
    def self.from_xml_element(person_element)
      @xml_element = person_element
      person = self.new
      person.person_id = person_element.elements["id"].text
      person.email = person_element.elements["email"].text
      person.name = person_element.elements["name"].text
      person.phone_number = person_element.elements["phone_number"].text
      return person
    end
  
    # Returns the XML representation of this person
    def to_xml
      return false if @xml_element.nil?
      @xml_element.text
    end
  
    # Creates this person record in the Tunecore system
    def create
      req = Request.new
      res = req.create_person(@email, @password, @name, @phone_number, @country, @postal_code)
      raise "Unexpected return type: #{res.type}" unless res.type == "person"
      if res.status == "complete"
        @person_id = res.object.person_id
        return true
      else
        @errors = res.errors
        return false
      end
    end
    
    # Creates a new album for this Person
    def create_album(params={})
      params[:person_id] = self.person_id
      album = TunecoreDirect::Album.new(params)
      album.create
      return album
    end
  
    # Returns an array of people associated with your account
    def self.get_people
      req = Request.new
      req.get_people.object
    end
    
    # Get's a person object from the TuneCore server.  Id can be either a person_id or an email address
    def self.get(id)
      req = Request.new
      req.get_person(id).object
    end
    
    # Returns an array of albums owned by this person
    def albums
      req = Request.new
      req.get_albums(person_id).object
    end
    
    
    
  end
end